<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Config;
use think\Session;
use think\Cache;
// 应用公共文件
/**
 * 密码加密方法
 * @param string $pw 要加密的原始密码
 * @param string $authCode 加密字符串
 * @return string
 */
function st_password($pw, $authCode = '')
{
    if (empty($authCode)) {
        $authCode = Config::get('database.authcode');
    }
    $result = "###" . md5(md5($authCode . $pw));
    return $result;
}
/**
 * 验证码检查，验证完后销毁验证码
 * @param string $value
 * @param string $id
 * @return bool
 */
function st_captcha_check($value, $id = "")
{
    $captcha = new \think\captcha\Captcha();
    return $captcha->check($value, $id);
}
/**
 * 检查手机或邮箱是否还可以发送验证码、保存到缓存并返回验证码
 * @param string $account 手机或邮箱
 * @param integer $length 验证码位数,支持4,6,8
 * @return string 数字验证码
 */
function st_get_verification_code($account)
{
    if (empty($account)) return false;
    $code                  = rand(100000, 999999);
    $verification['account'] = $account;
    $verification['time']   = time();
    $verification['code']   = $code;
    //Session::set('verification',$verification);
    $verificationCache = Cache::get('verification');
    Cache::set('verification',$verification,3600);
    foreach ($verification as $key=>$value){
        $value['pid'];
    }
    return $code;
}
/**
 * 检查验证码是否通过
 * @param string $account 手机或邮箱
 * @param integer $length 验证码位数,支持4,6,8
 * @return string 数字验证码
 */
function st_check_verification_code($account,$code)
{
    if (empty(Session::get('verification'))) return false;
    
    $verification = Session::get('verification');
    $code                  = rand(100000, 999999);
    $verification['account'] = $account;
    $verification['time']   = time();
    $verification['code']   = $code;
    Session::set('verification',$verification);

    
    return $code;
}
/**
 * 获取当前登录的前台用户的信息，未登录时，返回false
 * @return array|boolean
 */
function st_get_current_user()
{
    $sessionUser = session('user');
    if (!empty($sessionUser)) {
        return $sessionUser;
    } else {
        return false;
    }
}
/**
 * 更新当前登录前台用户的信息
 * @param array $user 前台用户的信息
 */
function st_update_current_user($user)
{
    session('user', $user);
}

/**
 * 获取当前登录前台用户id
 * @return int
 */
function st_get_current_user_id()
{
    $sessionUserId = session('user.id');
    if (empty($sessionUserId)) {
        return 0;
    }

    return $sessionUserId;
}

/**
 * 判断前台用户是否登录
 * @return boolean
 */
function st_is_user_login()
{
    $sessionUser = session('user');
    return !empty($sessionUser);
}
/**
 * 文件日志
 * @param $content 要写入的内容
 * @param string $file 日志文件,在web 入口目录
 */
function st_log($content, $file = "log.txt")
{
    file_put_contents($file, $content, FILE_APPEND);
}

/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function st_random_string($len = 6)
{
    $chars    = [
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    ];
    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}
/**
 * 判断是否为手机访问
 * @return  boolean
 */
function st_is_mobile()
{
    static $cmf_is_mobile;

    if (isset($cmf_is_mobile))
        return $cmf_is_mobile;

        $cmf_is_mobile = Request::instance()->isMobile();

        return $cmf_is_mobile;
}

/**
 * 判断是否为微信访问
 * @return boolean
 */
function st_is_wechat()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}


//模拟请求
function https_post($url, $type = "GET", $data = '')
{
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
    curl_setopt($ch,CURLOPT_HEADER,0);

    $type = strtolower($type);
    switch ($type){
        case 'get':
            break;
        case 'post':
            //post请求配置
            curl_setopt($ch, CURLOPT_POST,1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            break;
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


function http_post($remote_server, $post_data) {
        $ch = curl_init();//创建连接
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));//将数组转换为URL请求字符串，否则有些时候可能服务端接收不到参数
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); //接收服务端范围的html代码而不是直接浏览器输出
        curl_setopt($ch, CURLOPT_HEADER, false);
        $result = curl_exec($ch);//接受响应
        
        curl_close($ch);//关闭连接
        return  $result;
}

/** 文件转base64输出
 * @param  String $file 文件路径
 * @return String base64 string
 */
function fileToBase64($file){
    $base64_file = '';
    if(file_exists($file)){
        $mime_type= mime_content_type($file);
        $base64_data = base64_encode(file_get_contents($file));
        $base64_file = 'data:'.$mime_type.';base64,'.$base64_data;
    }
    return $base64_file;
}

/** base64转文件输出
 * @param  String $base64_data base64数据
 * @param  String $file        要保存的文件路径
 * @return boolean
 */
function base64ToFile($base64_data, $file){
    if(!$base64_data || !$file){
        return false;
    }
    return file_put_contents($file, base64_decode($base64_data), true);
}


//创建TOKEN
function createToken() {
    $code = chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) .       chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE));
    session('TOKEN', authcode($code));
}
//判断TOKEN
function checkToken($token) {
    if ($token == session('TOKEN')) {
        session('TOKEN', NULL);
        return TRUE;
    } else {
        return FALSE;
    }
}
/* 加密TOKEN */
function authcode($str) {
    $key = "cqsttzjt";
    $str = substr(md5($str), 8, 10);
    return md5($key . $str);
}

/**
 * @creator Jimmy
 * @data 2018/1/05
 * @desc 数据导出到excel(csv文件)
 * @param $filename 导出的csv文件名称 如date("Y年m月j日").'-test.csv'
 * @param array $tileArray 所有列名称
 * @param array $dataArray 所有列数据
 */
function exportToExcel($filename, $tileArray=[], $dataArray=[]){
    ini_set('memory_limit','512M');
    ini_set('max_execution_time',0);
    ob_end_clean();
    ob_start();
    header("Content-Type: text/csv");
    header("Content-Disposition:filename=".$filename);
    $fp=fopen('php://output','w');
    fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))
    
    fputcsv($fp,$tileArray);
    $index = 0;
    foreach ($dataArray as $item) {
        if($index==1000){
            $index=0;
            ob_flush();
            flush();
        }
        $index++;
        fputcsv($fp,$item);
    }

}